<?php
namespace app\admin\controller;
use think\Db;
use think\facade\Request;
class Entry extends Common
{
    /**录入员列表
     * URL：admin/entry/lists
     * @return array|mixed
     * @throws \think\exception\DbException
     */
    public function lists(){

        if (request()->isAjax()) {

            $keyword = input('post.keyword');
            $page =input('page',1);
            $pageSize =input('limit',config('pageSize'));

            $list = Db::name('performance_entry')->alias('pe')
                ->join('teacher t','t.id=pe.teacher_id','left')
                ->field('pe.*,t.teacher_no,t.true_name')
                ->where('pe.is_del',0)
                ->where('t.true_name|t.teacher_no', 'like', "%" . $keyword . "%")
                ->order('pe.create_time desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();

            if (! empty($list)) {

                foreach ($list['data'] as $k => $v) {

                    $list['data'][$k]['create_time'] = toDate($v['create_time']);
                    //分配部门
                    if ($v['section_ids']){
                        $section_ids = unserialize($v['section_ids']);
                        $str = '';
                        foreach ($section_ids as $k1=>$v1){
                            $t = Db::name('section')->where('section_id',$v1)->value('title');
                            $str .= $t.'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
                        }
                        $list['data'][$k]['section_ids'] = $str;
                    }

                }

            }

            return $result = ['code'=>0,'msg'=>'成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }

        return $this->fetch('entry_list');
    }

    /**
     * 查找录入员
     * @return array|mixed
     * @throws \think\exception\DbException
     */
    public function entry_search(){

        if(Request::isAjax()) {

            $keyword = input('post.keyword');
            $page =input('page',1);
            $pageSize =input('limit',config('pageSize'));
            $list = Db::name('teacher')
                ->field('id,teacher_no,true_name')
                ->where('is_del',0)
                ->where('id','neq',1)
                ->where('true_name|teacher_no', 'like', "%" . $keyword . "%")
                ->order('create_time desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();

            return $result = ['code'=>0,'msg'=>'成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        return $this->fetch('entryForm');
    }

    /**
     * 添加录入员
     */
    public function entryAdd(){
        $data['teacher_id'] = input('post.id');
        $data['create_time'] = time();
        $re = Db::name('performance_entry')->insert($data);
        $true_name = Db::name('teacher')->where('id',$data['teacher_id'])->value('true_name');
        $log = [
            'content'=>'添加录入员'.$true_name
        ];
        $wed = new Weblog();
        $res = $wed->insert($log);
        if ($re && $res){
            $this->success("设定成功",'lists');
        }
    }

    /**
     * 分配部门
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function distribution_section(){

        $id = (int)input('id');

        if (request()->isAjax()) {
            $data = input('post.');
            $data['section_ids'] = serialize($data['section_ids']);
            $re = Db::name('performance_entry')->where('id',$id)->update($data);
            $true_name = Db::name('performance_entry pe')->join('teacher t','t.id=pe.teacher_id')->where('pe.id',$id)->value('t.true_name');
            $log = [
                'content'=>'编辑审核部门'.$true_name
            ];
            $wed = new Weblog();
            $wed->insert($log);

            if(!$re){
                $this->error('编辑失败');
            }
            $this->success("编辑成功",'lists');

        }

        $sections = '';
        $info = Db::name('performance_entry')->where('id',$id)->find();

        if($info['section_ids']){
            $ids = implode(',',unserialize($info['section_ids']));
            $sections = Db::name('section')->field('section_id,title,pid')
                ->where('section_id','in',$ids)->select();
        }

        $this->assign('entry_id',$id);
        $this->assign('sections',$sections);
        return $this->fetch('distribution_section');

    }

    /**
     * 部门展示
     * @return array
     * @throws \think\exception\DbException
     */
    function section_list(){

        if (request()->isAjax()) {

            $page =input('page',1);
            $pageSize =input('limit',config('pageSize'));

            $list = Db::name('section')
                ->where('is_del',0)
                ->order('create_time desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();

            return $result = ['code'=>0,'msg'=>'成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }

    }

    /**删除录入员
     * URL：admin/entry/entryDel
     * @throws
     * @return array
     */
    public function entryDel(){
        $id=input('post.id');
        if (session('aid')==1){
            $re = Db::name('performance_entry')->where('id',$id)->update(['is_del'=>1]);
            $true_name = Db::name('performance_entry pe')->join('teacher t','t.id=pe.teacher_id')->where('pe.id',$id)->value('t.true_name');
            $log = [
                'content'=>'删除录入员'.$true_name
            ];
            $wed = new Weblog();
            $res = $wed->insert($log);
            if ($re && $res){
                $this->success('删除成功!');
            }else{
                $this->error('删除失败');
            }
        }else{
            $this->error('您没有删除录入员的权限!');
        }
    }




    /****************************录入列表***************************************************/

    /**
     * 录入列表
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index(){

        if (request()->isAjax()) {

            $keyword = input('post.keyword');
            $page =input('page',1);
            $pageSize =input('limit',config('pageSize'));

//          录入人员信息
            $info = Db::name('performance_entry')
                ->where('is_del',0)
                ->where('teacher_id',session('aid'))
                ->field('id,teacher_id as t_id,section_ids')
                ->find();

            if (!empty($info)&&$info&&$info['section_ids']) {

                //查找部门下的所有教师
                $section_ids = implode(',',unserialize($info['section_ids']));

                $arr = Db::name('teacher t')
                    ->join('section s','t.section_id=s.section_id')
                    ->where('t.true_name|t.teacher_no|s.title', 'like', "%" . $keyword . "%")
                    ->where('t.section_id','in',$section_ids)
                    ->field('t.id as teacher_id,t.teacher_no,t.true_name,t.section_id,s.title')
                    ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                    ->toArray();


                //查找今日可以编辑的考核项周期
                $cycle_data = Db::name('cycle')->where('status',1)->select();

                if($cycle_data) {
                    $str_cycle_ids = '';
                    foreach ($cycle_data as $k => $v) {

                        if ($v['id'] == 1) {

                            $today = (int)date("d", time());
                            if ((int)$v['start_time'] <= $today && (int)$v['end_time'] >= $today) {
                                $str_cycle_ids .= ','.$v['id'];
                            }
                        } elseif ($v['id'] == 2) {
                            $today = date("m-d", time());
                            if ($v['start_time'] && $v['end_time']) {
                                $start_time = unserialize($v['start_time']);
                                $end_time = unserialize($v['end_time']);
                                if ((($today >= $start_time[0]) && ($today <= $end_time[0])) || (($today >= $start_time[1]) && ($today <= $end_time[1]))) {
                                    $str_cycle_ids .= ','.$v['id'];
                                }
                            }
                        }elseif ($v['id'] == 3) {
                            $today = date("m-d",time());

                            if($v['start_time'] && $v['end_time'] && ($today>=$v['start_time'])&&($today<=$v['end_time'])){
                                $str_cycle_ids .= ','.$v['id'];
                            }
                        }
                    }

                    $tongji['zong'] = $arr['total'];
                    $tongji['dai'] = 0;
                    $tongji['cun'] = 0;
                    $tongji['jiao'] = 0;

                    //拿到所有教师
                    $teachers = Db::name('teacher t')
                        ->join('section s','t.section_id=s.section_id')
                        ->where('t.true_name|t.teacher_no|s.title', 'like', "%" . $keyword . "%")
                        ->where('t.section_id','in',$section_ids)
                        ->field('t.id as teacher_id,t.teacher_no,t.true_name,t.section_id,s.title')
                        ->select();

                    foreach ($teachers as $k2=>$v2) {

//                    拿到教师职务
                        $position_ids = Db::name('teacher')->where('id',$v2['teacher_id'])->value('position_id');

                        if($position_ids){
                            $str_position_ids = implode(',',array_keys(json_decode($position_ids,true)));
                        }

//                    根据职务拿到考核项分类ids
                        $performance_cate_ids = Db::name('teacher_position')->field('performance_cate_ids')->where('position_id','in',$str_position_ids)->select();

                        $str_performance_cate_ids = '';
                        if($performance_cate_ids){
                            foreach ($performance_cate_ids as $k=>$v){
                                if($v['performance_cate_ids']){
                                    $str_performance_cate_ids .= ','.implode(',',array_filter(array_unique(unserialize($v['performance_cate_ids']))));
                                }

                            }
                        }
                        $str_performance_cate_ids = implode(',',array_filter(array_unique(explode(',',$str_performance_cate_ids))));

//                    根据考核项分类ids和可编辑周期拿到可编辑考核项分类ids
                        $cate_list = Db::name('performance_cate')->where('cycle_id','in',$str_cycle_ids)->where('cate_id','in',$str_performance_cate_ids)->where('is_del',0)->field('cate_id,pid,title')->select();

                        $teachers[$k2]['dai']  = 0;
                        $teachers[$k2]['cun']  = 0;
                        $teachers[$k2]['jiao'] = 0;
                        $teachers[$k2]['tong'] = 0;
                        $teachers[$k2]['bo']   = 0;
                        $teachers[$k2]['shen'] = 0;

                        if($cate_list){

                            foreach ($cate_list as $k=>$v){

                                $answer = Db::name('answer_record')->where('teacher_id',$v2['teacher_id'])->where('performance_cate_id',$v['cate_id'])->find();

                                if($answer){

                                    if($answer['submit_status']==2||$answer['entry_submit_status']!=0){
                                        if($answer['entry_submit_status']=='0'){
                                            $teachers[$k2]['dai'] = (int)$teachers[$k2]['dai']+1;
                                        }elseif ($answer['entry_submit_status']==1){
                                            $teachers[$k2]['cun'] = (int)$teachers[$k2]['cun']+1;
                                        }else{
                                            $teachers[$k2]['jiao'] = (int)$teachers[$k2]['jiao']+1;
                                        }
                                    }else{
                                        $teachers[$k2]['dai'] = (int)$teachers[$k2]['dai']+1;
                                    }

                                    if($answer['entry_submit_status']==2){

                                        if($answer['second_status']==1&&$answer['status']==1){
                                            $teachers[$k2]['tong'] = (int)$teachers[$k2]['tong']+1;
                                        }elseif ($answer['second_status']==2||$answer['status']==2){
                                            $teachers[$k2]['bo'] = (int)$teachers[$k2]['bo']+1;
                                        }else{
                                            $teachers[$k2]['shen'] = (int)$teachers[$k2]['shen']+1;
                                        }

                                    }

                                }else{
                                    $teachers[$k2]['dai'] = (int)$teachers[$k2]['dai']+1;
                                }

                            }
                        }

                        if($teachers[$k2]['dai']==0&&$teachers[$k2]['cun']==0){
                            $teachers[$k2]['status_detail'] = '已完成';
                        }else{
                            $teachers[$k2]['status_detail'] = '待处理：'.$teachers[$k2]['dai'].'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;保存待提交：'.$teachers[$k2]['cun'].' &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;已提交：'.$teachers[$k2]['jiao'];
                        }

                        $teachers[$k2]['check_detail'] = '暂无提交';
                        if($teachers[$k2]['shen']==0&&$teachers[$k2]['bo']==0){
                            if($teachers[$k2]['tong']!=0){
                                $teachers[$k2]['check_detail'] = '已完成';
                            }
                        }else{
                            $teachers[$k2]['check_detail'] = '审核中：'.$teachers[$k2]['shen'].'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;驳回：'.$teachers[$k2]['bo'].' &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;通过：'.$teachers[$k2]['tong'];
                        }


                        if((int)$teachers[$k2]['dai']>0){
                            $tongji['dai'] = $tongji['dai']+1;
                        }

                        if((int)$teachers[$k2]['cun']>0){
                            $tongji['cun'] = $tongji['cun']+1;
                        }

                        if((int)$teachers[$k2]['jiao']>0){
                            $tongji['jiao'] = $tongji['jiao']+1;
                        }

                    }
//                    dump($teachers);
                    foreach ($arr['data'] as $k=>$v) {

                        foreach ($teachers as $k1=>$v1) {

                            if($v['teacher_id'] == $v1['teacher_id']){
                                $arr['data'][$k] = $v1;
                            }

                        }

                    }
                }

                return $result = ['code'=>0,'msg'=>'成功!','data'=>$arr['data'],'count'=>$arr['total'],'tongji'=>'待处理：'.$tongji['dai'].'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;保存待提交：'.$tongji['cun'].' &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;已提交：'.$tongji['jiao']];
            }else{
                return $result = ['code'=>0,'msg'=>'成功!','data'=>'','count'=>0,'tongji'=>'待处理：0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;保存待提交：0 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;已提交：0'];
            }


        }

        return $this->fetch();
    }


    /**
     * 个人考核项录入
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */

    public function entry_teacher(){
        $teacher_id = input('get.teacher_id');

        if (request()->isAjax()) {

            //查找今日可以编辑的考核项周期
            $cycle_data = Db::name('cycle')->where('status',1)->select();

            if($cycle_data) {
                $str_cycle_ids = '';
                foreach ($cycle_data as $k => $v) {

                    if ($v['id'] == 1) {

                        $today = (int)date("d", time());
                        if ((int)$v['start_time'] <= $today && (int)$v['end_time'] >= $today) {
                            $str_cycle_ids .= ','.$v['id'];
                        }
                    } elseif ($v['id'] == 2) {
                        $today = date("m-d", time());
                        if ($v['start_time'] && $v['end_time']) {
                            $start_time = unserialize($v['start_time']);
                            $end_time = unserialize($v['end_time']);
                            if ((($today >= $start_time[0]) && ($today <= $end_time[0])) || (($today >= $start_time[1]) && ($today <= $end_time[1]))) {
                                $str_cycle_ids .= ','.$v['id'];
                            }
                        }
                    }elseif ($v['id'] == 3) {
                        $today = date("m-d",time());

                        if($v['start_time'] && $v['end_time'] && ($today>=$v['start_time'])&&($today<=$v['end_time'])){
                            $str_cycle_ids .= ','.$v['id'];
                        }
                    }
                }


//                    拿到教师职务
                $position_ids = Db::name('teacher')->where('id',$teacher_id)->value('position_id');

                if($position_ids){
                    $str_position_ids = implode(',',array_keys(json_decode($position_ids,true)));
                }

//                    根据职务拿到考核项分类ids
                $performance_cate_ids = Db::name('teacher_position')->field('performance_cate_ids')->where('position_id','in',$str_position_ids)->select();

                $str_performance_cate_ids = '';
                if($performance_cate_ids){
                    foreach ($performance_cate_ids as $k=>$v){
                        if($v['performance_cate_ids']){
                            $str_performance_cate_ids .= ','.implode(',',array_filter(array_unique(unserialize($v['performance_cate_ids']))));
                        }

                    }
                }
                $str_performance_cate_ids = implode(',',array_filter(array_unique(explode(',',$str_performance_cate_ids))));

//                    根据考核项分类ids和可编辑周期拿到可编辑考核项分类ids
                $cate_list = Db::name('performance_cate')->where('cycle_id','in',$str_cycle_ids)->where('cate_id','in',$str_performance_cate_ids)->where('is_del',0)->field('cate_id,pid,title')->select();

                if($cate_list){
                    foreach ($cate_list as $k=>$v){

                        $answer = Db::name('answer_record')->where('teacher_id',$teacher_id)->where('performance_cate_id',$v['cate_id'])->find();
                        $cate_list[$k]['entry_submit_status'] = '教师暂未提交';

                        if($answer){

                            if(($answer['submit_status']==2)||($answer['entry_submit_status']!=0)){
                                $cate_list[$k]['entry_submit_status'] = $answer['entry_submit_status'];
                            }

                        }

                    }
                }

            }

            return $result = ['code'=>0,'msg'=>'成功!','data'=>$cate_list,'count'=>count($cate_list)];
        }
        $this->assign('teacher_id',$teacher_id);
        return $this->fetch('entry_teacher');
    }



    /**ajax请求对应题目分类下的题目数据
     * 具体考核项审核
     * @return mixed|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function entry_teacher_show(){

        $cate_id    = input('get.cate_id');
        $teacher_id = input('get.teacher_id');
        if(Request::isAjax()) {
            $cate_id    = input('get.cate_id');
            $teacher_id = input('get.teacher_id');

            //拿到该题目分类下的题目
            $performance_ids = Db::name('performance_cate')->where('cate_id',$cate_id)->value('performance_ids');
            $performance_ids = implode(',',unserialize($performance_ids));
            //查找题目并进行数据处理
            $list = Db::name('performance')->where('title_id','in',$performance_ids)->select();
            foreach ($list as $k=>$v){
                //没有做题时渲染题目
                $list[$k]['answer'] = '';
                $list[$k]['var_content'] = json_decode($v['var_content'],true);
            }

//            拿到分类周期
            $cycle_id = Db::name('performance_cate')->where('cate_id',$cate_id)->where('is_del',0)->value('cycle_id');

            //月度
            if($cycle_id==1){
                //        当前月份一号
                $first = date('Y-m',  time()).'-01';
                $start_time = strtotime($first);
                $end_time = strtotime( "$first +1 month");
//学期
            }elseif ($cycle_id==2){

                //        当前年份一号
                $first = date('Y',  time()).'-01-01';

                $start_time = strtotime($first);
                $end_time = strtotime( "$first +1 year");

//年度
            }elseif ($cycle_id==3){

                //        当前月份
                $month = date('m',  time());
//                下学期
                if($month>=2&&$month<8){
                    $first = date('Y',  time()).'-02-01';
                }else{
                    $first = date('Y',  time()).'-08-01';
                }
                $start_time = strtotime($first);
                $end_time = strtotime( "$first +6 month");

            }
            //通过$cate_id去数据库比对该教师是否已经做过了该题
            $info = Db::name('answer_record')->where('add_time',['>=',$start_time],['<',$end_time])->where('teacher_id',$teacher_id)->where('performance_cate_id',$cate_id)->find();

            $modify_remark = '';

            if (!empty($info)){
                $modify_remark = $info['modify_remark'];
                if($info['entry_submit_status']!=0){
                    $info['answer_content'] = unserialize($info['entry_answer_content']);
                }else{
                    $info['answer_content'] = unserialize($info['answer_content']);
                }

            }

            //如果存在
            if($info['answer_content']){
                foreach ($list as $k=>$v){
                    foreach ($info['answer_content'] as $k1=>$v1){

                        if ($v['title_id'] == $v1['tiu_id']){
                            $list[$k]['answer'] = $v1['answer'];
                        }
                    }
                }
            }

            $data['list'] = $list;
            $data['modify_remark'] = $modify_remark;
            return json($data);
        }

        $this->assign('cate_id',$cate_id);
        $this->assign('teacher_id',$teacher_id);

        return $this->fetch('entry_teacher_show');
    }


    /**
     * * 计算分数及月度考核初始页面展示
     * @return \think\response\View
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */

    public function title(){

        if(Request::isAjax()) {

            //计算并保存考核项答案
            $cate_id = input('get.cate_id');
            $modify_remark = input('get.modify_remark');
            $teacher_id = input('get.teacher_id');

//            拿到分类周期
            $cycle_id = Db::name('performance_cate')->where('cate_id',$cate_id)->where('is_del',0)->value('cycle_id');

            //月度
            if($cycle_id==1){
                //        当前月份一号
                $first = date('Y-m',  time()).'-01';
                $start_time = strtotime($first);
                $end_time = strtotime( "$first +1 month");
//学期
            }elseif ($cycle_id==2){

                //        当前年份一号
                $first = date('Y',  time()).'-01-01';

                $start_time = strtotime($first);
                $end_time = strtotime( "$first +1 year");

//年度
            }elseif ($cycle_id==3){

                //        当前月份
                $month = date('m',  time());
//                下学期
                if($month>=2&&$month<8){
                    $first = date('Y',  time()).'-02-01';
                }else{
                    $first = date('Y',  time()).'-08-01';
                }
                $start_time = strtotime($first);
                $end_time = strtotime( "$first +6 month");

            }

//            检查提交状态
            $submit_status = Db::name('answer_record')->where('teacher_id',$teacher_id)
                ->where('add_time',['>=',$start_time],['<',$end_time])->where('performance_cate_id',$cate_id)->find();
            if(isset($submit_status['entry_submit_status']) && $submit_status['entry_submit_status']==2){
                $this->error('您已提交，无权修改');
            }

//          获取参数
            $data = input('post.');
//            计算总分
            $total_score = 0;
            $jisuan = new Calculate();
            foreach ($data as $key=>$val){
                $total_score += call_user_func_array(array($jisuan,$key),$val);
            }
//          数据处理
            $result['score'] = $total_score;

            $answer_data = array();
            foreach ($data as $k=>$v){
                $answer = array();
                $answer['tiu_id'] = substr($k,4);
                $answer['answer'] = $v;
                $answer_data[] = $answer;
            }
            $result['entry_answer_content']=serialize($answer_data);

            $result['entry_submit_status'] = input('get.flag');
            $result['modify_remark'] = $modify_remark;

//            判断是否为第一次编辑 是则插入数据库  否则更新数据
            if (isset($submit_status)){
                $re = Db::name('answer_record')->where('teacher_id',$teacher_id)->where('performance_cate_id',$cate_id)->update($result);
            }else{
                $result['performance_cate_id'] = $cate_id;
                $result['add_parentname'] = session('username');
                $result['teacher_id'] = $teacher_id;
                $result['add_time'] = time();
                $re = Db::name('answer_record')->insert($result);
            }
//          网站日志
            $title = Db::name('performance_cate')->where('cate_id',$result['performance_cate_id'])->value('title');
            $log = [
                'content'=>'保存考核项'.$title
            ];
            $wed = new Weblog();
            $res = $wed->insert($log);
//            返回计算结果
            if ($re && $res){

                $this->success('本次总分为：'.$total_score);
            }

        }else{
            return view('entry_teacher_show');
        }
    }
}